<?php


class Ext_Image_Upload
{
    protected $_datas    = array();
    protected $_messages = array();
    
    public function __construct()
    {
    }
    
    public function upload()
    {
        $result = array(
            'code'     => Ext_Image_Upload_Result::FAILURE,
            'data'     => new stdClass(),
            'messages' => array(),
        );
        
        $userId = Ext_Auth_Front::getInstance()->getIdentity();
        $config = Ext_Config::getInstance()->getConfig('image');
                
        $tmpPath = rtrim($config->graphics->tmp, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'upload' . DIRECTORY_SEPARATOR;
        Ext_Utility_File::prepareDir($tmpPath);

        $upload = new Zend_File_Transfer();
        $fileInfos = $upload->getFileInfo();
        foreach ( $fileInfos as $file=>$fileInfo )
        {
            if (!$upload->isUploaded($file)) {
                continue;
            }
            break;
        }
        
        $upload->setDestination($tmpPath);
        $isImage = new Ext_Validate_IsImage($config->upload->extension);
        $upload->addValidator($isImage, true);
        $upload->addValidator('Size', false, $config->upload->maxsize);
    
        if(!$upload->isValid($file)){
            $result['messages'] = $upload->getMessages();
            return new Ext_Image_Upload_Result($result['code'], $result['data'], $result['messages']);
        }
        $ext = Ext_Utility_File::getImageType($fileInfo['tmp_name']);
        $target = $tmpPath.time().'_'.$userId.'_'.Ext_Utility_String::random(6).'.'.$ext;
        $upload->addFilter('Rename', array('target'=>$target, 'overwrite'=>true), $file);
        $upload->receive($file);
        
        $data = new stdClass();
        $data->name = $fileInfo['name'];
        $data->file = $upload->getFileName($file, true);
        $result['code'] = Ext_Image_Upload_Result::SUCCESS;
        $result['data'] = $data;
        return new Ext_Image_Upload_Result($result['code'], $result['data'], $result['messages']);
    }
    
}
